package com.daiziru.schedules;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daiziru.common.constant.RedisConstants;
import com.daiziru.entity.MPost;
import com.daiziru.service.MPostService;
import com.daiziru.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class ViewCountSyncTask {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MPostService postService;


    @Scheduled(cron = "0 0/60 * * * ?") //每60分钟执行同步缓存到数据库
    public void task() {
        //1、从缓存获取所有需要更新到数据库里面的文章的id
        //获取所有的viewCount:post:下的key
        Set<String> keys = redisTemplate.keys(RedisConstants.VIEWCOUNT_POST + "*");
        //从缓存获取所有需要更新到数据库里面的文章的id
        List<String> ids = new ArrayList<>();
        for (String key : keys) {
            if(redisUtil.hHasKey(key, "post:viewCount")){
                ids.add(key.substring(RedisConstants.VIEWCOUNT_POST.length()));
            }
        }
        if(ids.isEmpty()) return;

        // 需要更新阅读量
        List<MPost> posts = postService.list(new QueryWrapper<MPost>().in("id", ids));
        posts.stream().forEach((post) ->{
            Integer viewCount = (Integer) redisUtil.hget(RedisConstants.VIEWCOUNT_POST + post.getId(), "post:viewCount");
            post.setViewCount(viewCount);
        });
        if(posts.isEmpty()) return;
        boolean isSuccess = postService.updateBatchById(posts);
        if(isSuccess) {
            System.out.println("-------------------------> viewCount更新成功！");
//            ids.stream().forEach((id) -> {
//                redisUtil.hdel(RedisConstants.VIEWCOUNT_POST + id, "post:viewCount");
//                System.out.println("post:" + id + "---------------------->同步成功");
//            });
        }
    }

}
